<?php defined('RUN_KATANA') or die('Restricted access');
class ShopQuestion extends Object
{
	public $Title;
	public $Active;
	public $Answers;
	public $ResponsesCount;
	
	public function __toString()
	{
		$out  = self::getTitle();
		return $out;
	}
	
	public function getActive() { return intval($this->Active); }
	public function getResponsesCount()
	{ 
		self::loadRensponsesCount();
		return intval($this->ResponsesCount); 
	}
	
	public function setActive($val) { $this->Active=intval($val); }
	
	public function update()
	{
		if((self::getId() > 0) && (self::getDataChanged()))
		{
			$sql  = 'UPDATE '.DB_PERFIX.'shop_questions SET ';
			$sql .= '`title`="'.self::formatText(self::getTitle()).'", ';
			$sql .= '`active`='.self::getActive().', ';
			$sql .= ' WHERE id='.self::getId().' LIMIT 1;';
			mysql_query($sql);
		}
	}
	
	/* Answers */
	public function getAnswers() 
	{
		self::loadAnswers();
		return $this->Answers; 
	}
	
	public function loadAnswers() 
	{
		global $db;
		if(self::getId() > 0)
		{
			$sql  = 'SELECT * FROM '.DB_PERFIX.'shop_question_answers WHERE question_id='.self::getId().';';
			$data = $db->fetch($sql, CACHE_TTL);
			if(is_array($data))
			{
				foreach($data as $row)
				{
					$this->Answers[$row['id']] = new ShopQuestionAnswer();
					$this->Answers[$row['id']]->setId($row['id']);
					$this->Answers[$row['id']]->setType($row['type']);
					$this->Answers[$row['id']]->setTitle($row['title']);
					$this->Answers[$row['id']]->setActive($row['active']);
				}
			}
		}
	}
	
	public function loadRensponsesCount() 
	{
		if(!self::getItemLoaded('ResponsesCount'))
		{
			global $db;
			if(self::getId() > 0)
			{
				$sql  = 'SELECT COUNT(id) AS ResponsesCount FROM '.DB_PERFIX.'shop_question_responses WHERE question_id='.self::getId().';';
				$data = $db->fetch($sql, CACHE_TTL);
				if(is_array($data))
				{
					foreach($data as $row)
					{ self::setResponsesCount($row['ResponsesCount']); }
				}
			}
			unset($data);
			self::setItemLoaded('ResponsesCount', true);
		}
	}
	
	public function getPercent($count=0)
	{
		$percent = 0;
		if(($count > 0) && (self::getResponsesCount() > 0))
		{ $percent = round((($count / self::getResponsesCount()) * 100), 1); }
		return $percent;
	}
}
?>